<template>
  <div
    style="width: 100%; height: 100%"
    @mousedown="domMousedown"
    ref="canvasMainRef"
  >
    <draw
      v-if="checkFigure"
      @drawChange="setSvgPosition"
      @xwChange="setSvgWidthAndHeight"
      v-model="checkFigure"
    />
    <svg
      ref="svg"
      class="svgClass"
      xmlns="http://www.w3.org/2000/svg"
      version="1.1"
      :width="`${width}px`"
      :height="`${height}px`"
    >
      <rect
        ref="mainRect"
        style="fill: #fff; stroke-width: 1; stroke: rgb(0, 0, 0)"
        :width="mainConfig.w"
        :height="mainConfig.h"
        :x="mainConfig.x"
        :y="mainConfig.y"
        @click="checkFigure = null"
      ></rect>

      <!-- 	<foreignObject x="509" y="211" width="200" height="100">
				<input type="text" value="Hello World!" style="color: black;" />
			</foreignObject> -->
      <component
        v-for="(item, index) in $store.state.tags"
        :key="index"
        :is="item.name"
        v-model="item.data"
        :lid="item.id"
      ></component>
    </svg>
  </div>
</template>
<script>
// var Enumerable = require("linq");
import Enumerable from "linq";
import { mapState, mapMutations } from "vuex";
import svgLine from "./SvgComp/SvgLine.vue";
import svgRect from "./SvgComp/SvgRect.vue";
import draw from "@/components/Draw/Draw.vue";
import svgFont from "./SvgComp/SvgFont.vue";
import svgImage from "./SvgComp/SvgImage.vue";
import svgQrCode from "./SvgComp/SvgQrCode.vue";
import svgBarcode from "./SvgComp/SvgBarcode.vue";
export default {
  components: {
    draw,
    svgLine,
    svgRect,
    svgFont,
    svgImage,
    svgQrCode,
    svgBarcode,
  },
  data() {
    return {
      width: 0,
      height: 0,
      mainConfig: {
        x: 0,
        y: 0,
        w: 800,
        h: 600,
      },
      tags: [],
      copyTags: [],
      keyboard: {
        Ctrl: false,
        Shift: false,
        Enter: false,
        Esc: false,
        Delete: false,
      },
      testx: 0,
      testy: 0,
      //选择的图形,先做单个选择 后期如果需要 可以做多个
      checkFigure: null,
    };
  },
  watch: {
    checkTool(newVal, oldVal) {
      if (this.checkTool != "cursor") {
        this.checkFigure = null;
      }
    },
    keyboard: {
      handler(oldVal, newVal) {
        if (newVal.Delete && this.checkFigure) {
          var tagIndex = this.$store.state.tags.findIndex(
            (p) => p.id == this.checkFigure.id
          );
          this.$store.state.tags.splice(tagIndex, 1);
          this.checkFigure = null;
        }
        if (newVal.Esc && this.checkFigure) {
          this.checkFigure = null;
        }
      },
      deep: true,
    },
    "$store.state.figureParameter": {
      // immediate: true,
      handler: function (newName, oldName) {
        console.log(newName);
        this.setBorderSize();
      },
      deep: true,
    },
  },
  mounted() {
    //设置标签居中事件
    this.getDomCenter();
    //监听键盘事件
    this.initKeyboard();
    this.$nextTick(() => {});
  },
  props: {
    checkTool: null,
  },
  methods: {
    ...mapMutations([
      "changeframeType",
      "changeParameter",
      "changebeforeId",
      "changeImgs",
      "changeencoded",
    ]),
    //监听键盘按钮事件
    initKeyboard() {
      document.onkeydown = (e) => {
        if (e.code == "Tab") this.keyboard.Tab = true;
        if (e.code == "ControlLeft") this.keyboard.Ctrl = true;
        if (e.code == "ShiftLeft") this.keyboard.Shift = true;
        if (e.code == "Escape") this.keyboard.Esc = true;
        if (e.code == "Delete") this.keyboard.Delete = true;
      };
      document.onkeyup = (e) => {
        if (e.code == "Tab") this.keyboard.Tab = false;
        if (e.code == "ControlLeft") this.keyboard.Ctrl = false;
        if (e.code == "ShiftLeft") this.keyboard.Shift = false;
        if (e.code == "Escape") this.keyboard.Esc = false;
        if (e.code == "Delete") this.keyboard.Delete = false;
      };
    },
    //获取中间位置
    getDomCenter() {
      const dom = this.$refs.svg;
      var pHeight = dom.parentNode.clientHeight;
      var pWidth = dom.parentNode.clientWidth;
      console.log(pWidth);
      this.width = pWidth;
      this.height = pHeight;
      //设置主面板居中
      const rectMain = this.$refs.mainRect;
      const rWidth = rectMain.getAttribute("width");
      const rHeight = rectMain.getAttribute("height");
      this.mainConfig.x = (pWidth - rWidth) / 2;
      this.mainConfig.y = (pHeight - rHeight) / 2;
    },
    //鼠标左键按下事件
    domMousedown(el) {
      //防止点击错误生成
      //记录开始时间 在鼠标弹起后计时 如果不到100ms 就当是误触
      var startTime = new Date().valueOf();

      //如果不是点击"选择"按钮 那么保存它运行的每一步 以防弄错可以撤销
      if (
        el.offsetX < this.mainConfig.x ||
        el.offsetX > this.mainConfig.x + this.mainConfig.w ||
        el.offsetY < this.mainConfig.y ||
        el.offsetY > this.mainConfig.y + this.mainConfig.h
      ) {
        return;
      }
      if (this.checkTool != "cursor") {
        this.copyData();
      }

      //获取ref 并获取他所在屏幕的X，Y轴
      var canvasMainRef = this.$refs.canvasMainRef;
      const startX = el.offsetX;
      const startY = el.offsetY;
      var timestamp = new Date().valueOf();
      var data = {};

      //判断如果点击的是线
      if (this.checkTool == "line") {
        data = {
          name: "svg-line",
          id: timestamp,
          data: {
            x1: startX,
            x2: startX,
            y1: startY,
            y2: startY,
            click: this.addClick,
          },
        };
        this.$store.state.tags.push(data);
      }
      if (this.checkTool == "juxing") {
        data = {
          name: "svg-rect",
          id: timestamp,
          data: {
            x1: startX,
            h1: 0,
            y1: startY,
            w1: 0,
            click: this.addClick,
          },
        };
        this.$store.state.tags.push(data);
      }
      if (this.checkTool == "image") {
        data = {
          name: "svg-image",
          id: timestamp,
          data: {
            x1: startX,
            h1: 0,
            y1: startY,
            w1: 0,
            click: this.addClick,
            imgValue: null,
          },
        };
        this.$store.state.tags.push(data);
      }
      if (this.checkTool == "twoCode") {
        data = {
          name: "svg-qr-code",
          id: timestamp,
          data: {
            x1: startX,
            h1: 0,
            y1: startY,
            w1: 0,
            click: this.addClick,
            imgValue: null,
          },
        };
        this.$store.state.tags.push(data);
      }
      if (this.checkTool == "oneCode") {
        data = {
          name: "svg-barcode",
          id: timestamp,
          data: {
            x1: startX,
            h1: 0,
            y1: startY,
            w1: 0,
            click: this.addClick,
            imgValue: null,
          },
        };
        this.$store.state.tags.push(data);
      }
      if (this.checkTool == "font") {
        var isExist = Enumerable.from(this.$store.state.tags)
          .where((p) => p.name == "svg-font" && p.data.focus)
          .any();
        if (isExist) return;

        data = {
          name: "svg-font",
          id: timestamp,
          data: {
            value: "",
            x1: startX,
            y1: startY,
            w1: 30,
            h1: 30,
            fontSize: 16,
            focus: true,
            click: this.addClick,
          },
        };
        this.$store.state.tags.push(data);
      }

      // newDom.addEventListener("click",(e)=>{
      // 	console.log(e);
      // })
      //添加鼠标移动事件
      canvasMainRef.onmousemove = (e) => {
        if (this.checkTool == "line") {
          //判断是否按下了shift键，如果按下了只能直线或者45°或向Y
          if (this.keyboard.Shift) {
            var range = e.offsetX - startX;
            var negative = startX - e.offsetX;
            //判断鼠标光标在长度是否在X的范围内
            if (range * 0.5 > e.offsetY - startY) {
              //横线
              data.data.x2 = e.offsetX;
              data.data.y2 = startY;
            }
            //todo...
            // else if (range * 0.3 < (e.offsetY - startY) && range * 0.6 > (e.offsetY - startY)) {
            //     //45°斜线
            //     //data.data.y2 = (startY + e.offsetY -startY);
            // }
            else if (range * 0.5 < e.offsetX - startY) {
              data.data.y2 = e.offsetY;
              data.data.x2 = startX;
            }
          } else {
            data.data.y2 = e.offsetY;
            data.data.x2 = e.offsetX;
          }
          for (var i = 0; i < this.$store.state.tags.length; i++) {
            if (this.$store.state.tags[i].id == timestamp) {
              this.$store.state.tags[i] == data;
            }
          }
        }
        if (this.checkTool == "juxing") {
          //判断不是往负方向来拖拽

          if (this.keyboard.Shift) {
            if (e.offsetX - startX > 0) {
              //data.data.w1 =  e.offsetX - startX;
              data.data.w1 =
                e.offsetX - startX > e.offsetY - e.offsetY
                  ? e.offsetX - startX
                  : e.offsetY - e.offsetY;
            }
            if (e.offsetY - startY > 0) {
              data.data.h1 =
                e.offsetX - startX > e.offsetY - e.offsetY
                  ? e.offsetX - startX
                  : e.offsetY - e.offsetY;
            }
            if (e.offsetX - startX <= 0) {
              data.data.x1 = e.offsetX;
              data.data.w1 = startX - e.offsetX;
            }
            if (e.offsetY - startY <= 0) {
              data.data.y1 = e.offsetY;
              data.data.h1 = startY - e.offsetY;
            }
          } else {
            if (e.offsetX - startX > 0) {
              data.data.w1 = e.offsetX - startX;
            }
            if (e.offsetY - startY > 0) {
              data.data.h1 = e.offsetY - startY;
            }
            if (e.offsetX - startX <= 0) {
              data.data.x1 = e.offsetX;
              data.data.w1 = startX - e.offsetX;
            }
            if (e.offsetY - startY <= 0) {
              data.data.y1 = e.offsetY;
              data.data.h1 = startY - e.offsetY;
            }
          }

          for (var i = 0; i < this.$store.state.tags.length; i++) {
            if (this.$store.state.tags[i].id == timestamp) {
              this.$store.state.tags[i] == data;
            }
          }
        }
        if (
          this.checkTool == "image" ||
          this.checkTool == "twoCode" ||
          this.checkTool == "oneCode"
        ) {
          //判断不是往负方向来拖拽

          if (this.keyboard.Shift) {
            if (e.offsetX - startX > 0) {
              //data.data.w1 =  e.offsetX - startX;
              data.data.w1 =
                e.offsetX - startX > e.offsetY - e.offsetY
                  ? e.offsetX - startX
                  : e.offsetY - e.offsetY;
            }
            if (e.offsetY - startY > 0) {
              data.data.h1 =
                e.offsetX - startX > e.offsetY - e.offsetY
                  ? e.offsetX - startX
                  : e.offsetY - e.offsetY;
            }
            if (e.offsetX - startX <= 0) {
              data.data.x1 = e.offsetX;
              data.data.w1 = startX - e.offsetX;
            }
            if (e.offsetY - startY <= 0) {
              data.data.y1 = e.offsetY;
              data.data.h1 = startY - e.offsetY;
            }
          } else {
            if (e.offsetX - startX > 0) {
              data.data.w1 = e.offsetX - startX;
            }
            if (e.offsetY - startY > 0) {
              data.data.h1 = e.offsetY - startY;
            }
            if (e.offsetX - startX <= 0) {
              data.data.x1 = e.offsetX;
              data.data.w1 = startX - e.offsetX;
            }
            if (e.offsetY - startY <= 0) {
              data.data.y1 = e.offsetY;
              data.data.h1 = startY - e.offsetY;
            }
          }

          for (var i = 0; i < this.$store.state.tags.length; i++) {
            if (this.$store.state.tags[i].id == timestamp) {
              this.$store.state.tags[i] == data;
            }
          }
        }
      };
      //鼠标谈起事件
      canvasMainRef.onmouseup = (evt) => {
        //防止误触事件
        var tag = this.$store.state.tags.find((p) => p.id == timestamp);
        if (tag) {
          //防止误触
          this.miscontact(timestamp, startTime);
          if (tag.name == "svg-qr-code") tag.data.imgValue = "CH Control";
          if (tag.name == "svg-barcode") tag.data.imgValue = "CH Control";
        }
        canvasMainRef.onmousemove = (evt) => {};
        //获取SVG图标
        //console.log(document.getElementById(timestamp).getBoundingClientRect().width, document.getElementById(timestamp).getBoundingClientRect().height);
      };
    },
    /**
     * 开启叠层误触事件，防止在叠层上面点击变成添加dom事件
     * @param {*} id 新增的dom唯一ID
     * @param {*} startTime 点击的时间错
     */
    miscontact(id, startTime) {
      var endTime = new Date().valueOf();

      if (endTime - startTime < 100) {
        var tagIndex = this.$store.state.tags.findIndex((p) => p.id == id);
        this.$store.state.tags.splice(tagIndex, 1);
      }
    },
    //变动宽高
    setSvgWidthAndHeight(id, w, h) {
      var tag = this.$store.state.tags.find((p) => p.id == id);
      if (!tag) return;
      tag.data.w1 = w;
      tag.data.h1 = h;
      if (tag.name == "svg-line") {
        tag.data.x2 = tag.data.x1 + w;
        tag.data.y2 = tag.data.y1 + h;
      }
    },
    //拖拽变动
    setSvgPosition(id, x, y, w, h) {
      var tag = this.$store.state.tags.find((p) => p.id == id);
      if (!tag) return;
      var windowRem = (document.documentElement.clientWidth / 1920) * 16;
      var menuWidth = windowRem * 4;
      var headerHeight = windowRem * 2.5;
      tag.data.x1 = x - menuWidth - 2;
      tag.data.y1 = y - headerHeight;
      tag.data.h1 = h;
      tag.data.w1 = w;
      if (tag.name == "svg-line") {
        tag.data.x2 = tag.data.x1 + w;
        tag.data.y2 = tag.data.y1 + h;
      }
      if (tag.name == "svg-juxing") {
        console.log(tag.name);
      }
    },
    getJson() {
      var result = [];
      var mainConfig = this.mainConfig;
      var tags = JSON.parse(JSON.stringify(this.$store.state.tags));
      tags.forEach((item) => {
        if (item.data["x1"] != undefined) {
          item.data["x1"] = item.data["x1"] - mainConfig.x;
        }
        if (item.data["x2"] != undefined) {
          item.data["x2"] = item.data["x2"] - mainConfig.x;
        }
        if (item.data["y1"] != undefined) {
          item.data["y1"] = item.data["y1"] - mainConfig.y;
        }
        if (item.data["y2"] != undefined) {
          item.data["y2"] = item.data["y2"] - mainConfig.y;
        }
        result.push(item);
      });
      console.log(result);

      return {
        ...this.mainConfig,
        tags: result,
      };
    },
    addClick(id) {
      const tagInfo = this.$store.state.tags.filter((item) => item.id == id);
      const [tag] = tagInfo;
      if (tag) {
        this.changebeforeId(id);
        this.changeParameter(tag.data);
        this.changeframeType(tag.name);
        //图片
        if (tag.name == "svg-image") {
          const data = {
            localityimgurl: tag.data.localityname,
            networkimgurl: tag.data.networkImg,
          };
          this.changeImgs(data);
        }
        //二维码
        if (tag.name == "svg-qr-code") {
          const data = {
            sourcesID: tag.data.sourcesID,
            dataFieldID: tag.data.dataFieldID,
            dictionaryName: tag.data.dictionaryName,
          };
          this.changeencoded(data);
        }
        //一维码
        if (tag.name == "svg-barcode") {
          const data = {
            sourcesID: tag.data.sourcesID,
            dataFieldID: tag.data.dataFieldID,
            dictionaryName: tag.data.dictionaryName,
          };
          this.changeencoded(data);
        }
        //文本
        if (tag.name == "svg-font") {
          const data = {
            sourcesID: tag.data.sourcesID,
            dataFieldID: tag.data.dataFieldID,
            dictionaryName: tag.data.dictionaryName,
            fontSize: tag.data.fontSize,
          };
          this.changeencoded(data);
        }
      }
      if (this.checkTool == "cursor") {
        var dom = document.getElementById(id);
        if (!dom) return;

        if (this.checkFigure && this.checkFigure.id == id) return;
        var domSpecification = dom.getBoundingClientRect().toJSON();
        this.checkFigure = {
          ...domSpecification,
          id: id,
        };
      }
    },
    setBorderSize(id) {
      if (this.checkFigure) {
        var id = this.checkFigure.id;
        var dom = document.getElementById(id);
        var domSpecification = dom.getBoundingClientRect().toJSON();
        console.log(domSpecification);
        this.checkFigure = {
          ...domSpecification,
          id: id,
        };
        this.checkFigure.width = this.$store.state.figureParameter.w1;
        this.checkFigure.height = this.$store.state.figureParameter.h1;
      }
    },
    setTags(data) {
      this.checkFigure = null;
      var tags = JSON.parse(JSON.stringify(data));

      var mainConfig = JSON.parse(JSON.stringify(this.mainConfig));
      var result = [];
      tags.map((item) => {
        const { data } = item;
        data.click = this.addClick;
        if (item.data.x1) {
          data.x1 = data.x1 + mainConfig.x;
        }
        if (item.data.x2) {
          data.x2 = data.x2 + mainConfig.x;
        }
        if (item.data.y1) {
          data.y1 = data.y1 + mainConfig.y;
        }
        if (item.data.y2) {
          data.y2 = data.y2 + mainConfig.y;
        }

        // result.push(obj);
      });
      console.log();
      this.$store.state.tags = tags;
    },
    clearTags() {
      this.checkFigure = null;
      this.$store.state.tags = [];
    },
    //备份好每一步
    copyData() {
      if (this.$store.state.tags == undefined) {
        this.$store.state.tags = [];
      }
      this.copyTags.push(JSON.parse(JSON.stringify(this.$store.state.tags)));
    },
    //撤销上一步
    cancelStep() {
      if (this.copyTags.length > 0) {
        this.$store.state.tags = this.copyTags[this.copyTags.length - 1];
        delete this.copyTags[this.copyTags.length - 1];
      }
    },
  },
};
</script>
<style lang="less"></style>
